package cn.liziguo.tank.script;

import cn.liziguo.tank.config.GameConfig;
import cn.liziguo.tank.constants.ImageConst;
import com.almasb.fxgl.animation.Interpolators;
import com.almasb.fxgl.dsl.FXGL;
import com.almasb.fxgl.entity.component.Component;
import com.almasb.fxgl.texture.Texture;
import javafx.animation.TranslateTransition;
import javafx.util.Duration;

/**
 * @author Liziguo
 * @date 2022/7/29 10:29
 */
public class GameOverComponent extends Component {

    public static final int GOTO_MAIN_MENU_DELAY = 5000;
    public static final int TRANSITION_TIME = 2500;
    public static final int SCALE = 5;

    private long gotoMainMenuTime;

    private Texture texture;

    @Override
    public void onAdded() {
        Texture texture;
        FXGL.getGameScene().getContentRoot().getChildren().add(this.texture = texture = FXGL.texture(ImageConst.GAME_OVER));
        texture.setScaleX(SCALE);
        texture.setScaleY(SCALE);
        TranslateTransition translateTransition = new TranslateTransition(Duration.millis(TRANSITION_TIME), texture);
        translateTransition.setFromX(GameConfig.WIDTH / 2.0 - texture.getWidth() / 2.0);
        translateTransition.setFromY(FXGL.getAppHeight());
        translateTransition.setToY(GameConfig.HEIGHT / 2.0 - texture.getHeight() / 2.0);
        translateTransition.setInterpolator(Interpolators.ELASTIC.EASE_OUT());
//        translateTransition.setInterpolator(Interpolator.EASE_BOTH);
        // translateTransition.setOnFinished(actionEvent -> {});
        gotoMainMenuTime = System.currentTimeMillis() + GOTO_MAIN_MENU_DELAY;
        translateTransition.play();
    }

    @Override
    public void onUpdate(double tpf) {
        if (System.currentTimeMillis() >= gotoMainMenuTime) {
            FXGL.getGameScene().getContentRoot().getChildren().remove(texture);
            FXGL.getGameController().gotoMainMenu();
        }
    }

    @Override
    public void onRemoved() {
        FXGL.getGameScene().getContentRoot().getChildren().remove(texture);
    }
}
